#!/usr/bin/env python3
import os
import subprocess

# 工作目录
workdir = '/home/stest/docker/shop-boot'
# 镜像名称
image_name = ''


def del_container():
    print('')
    print('删除容器')
    (status, output) = run_shell('docker ps -a -q --filter name=shop-boot-test')
    if len(output) > 0:
        run_shell('docker rm -f ' + output)


def init_env():
    global image_name
    global workdir
    fs = os.listdir(workdir)

    for f in fs:
        if f.endswith('.tar'):
            image_name = f[:-4]
    print('镜像名称:' + image_name)


def has_image():
    """
    判断本地是否已经存在项目对应的分支和版本的镜像
    :return: True | False
    """
    print('')
    print('搜索本地镜像')
    global image_name
    (status, output) = run_shell(
        'docker images -q --filter=reference=' + image_name)

    if 0 == status:
        if 0 == len(output):
            return False
        else:
            return True


def del_image():
    print('')
    print('删除镜像')
    global image_name
    run_shell('docker rmi ' + image_name)


def load_image():
    print('')
    print('加载镜像')
    global image_name
    run_shell('docker load -i /home/stest/docker/shop-boot/' + image_name + '.tar')


def run_container():
    print('')
    print('运行容器')
    run_shell(
        'docker run -d --name shop-boot-test --link=mysql-3306:mysql --link=redis-6379:redis --privileged=true -p '
        '8091:8091 -v /home/stest/docker/shop-boot/conf:/etc/shop-boot/conf -v '
        '/home/stest/docker/shop-boot/logs:/var/log/shop-boot shop-boot-test:0.1')


def run_shell(sh):
    print('====================================================')
    print('shell:' + sh)
    (status, output) = subprocess.getstatusoutput(sh)
    print('shell status:', status)
    print('shell output:')
    print(output)
    print('====================================================')
    print('')
    return status, output


if __name__ == '__main__':
    init_env()
    del_container()
    if has_image():
        del_image()
    load_image()
    run_container()